var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var morgan = require('morgan');
// 导入session
const session = require('express-session');
// 用户路由
var usersRouter = require('./routes/users');
// 管理员路由
var adminRouter = require('./routes/admin');
//管理文章路由
const topicRouter = require('./routes/topic');
// 基础路由
const indexRouter = require('./routes/index');
// 路由token验证
const {
  verifyUser,
  verifyAdmin,
  verifyTopic,
} = require('./common/verifyToken');
//模型外键关联
require('./model/init_model');
/* 图片上传 */
var app = express();
/* 日志保存 */
const { returnDate } = require('./common/returnDataFormat');
const fs = require('fs');
const filePath = path.join(__dirname, './logs/log.txt');
const accessLogStream = fs.createWriteStream(filePath, { flags: 'a' });
//自定义日志类型
app.use(
  morgan(
    function (tokens, req, res) {
      return [
        tokens.method(req, res),
        tokens.url(req, res),
        tokens.status(req, res),
        tokens.res(req, res, 'content-length'),
        '-',
        tokens['response-time'](req, res),
        'ms',
        '-',
        returnDate(tokens.date(req, res)),
      ].join(' ');
    },
    { stream: accessLogStream }
  )
);
/* 跨域请求开放 */
app.all('*', function (req, res, next) {
  //设置允许跨域的域名，*代表允许任意域名跨域
  res.header('Access-Control-Allow-Origin', '*');
  //允许的header类型
  res.header('Access-Control-Allow-Headers', '*');
  //跨域允许的请求方式
  res.header('Access-Control-Allow-Methods', 'DELETE,PUT,POST,GET,OPTIONS');
  if (req.method.toLowerCase() == 'options') res.send(200);
  //让options尝试请求快速结束
  else next();
});
// 使用session中间件
app.use(
  session({
    secret: 'keyboard cat',
    resave: true,
    saveUninitialized: true,
  })
);
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', verifyUser, usersRouter);
app.use('/admin', verifyAdmin, adminRouter);
app.use('/topic', verifyTopic, topicRouter);
app.use('/uploads/', express.static(path.join(__dirname, './uploads/')));

module.exports = app;
